﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Ajax.Utilities;

namespace EasySolutionForAll.Models.Quiz
{
    public class CsvMapModel
    {
        public string Category { get; set; }
        public string Question { get; set; }
        public string Answer { get; set; }
        public bool? CorrectAnswer { get; set; }
        public int? Level { get; set; }
        public bool? IsVisible { get; set; }

        public int? Order { get; set; }

        public static void Submit(List<CsvMapModel> rows)
        {
            if (rows.Any())
            {
                using (var db = new ApplicationDbContext())
                {
                    for (int index = 0; index < rows.Count;)
                    {
                        var row = rows[index];
                        var answer = row.Answer.Split(',').ToList();
                        QuestionSet questionSet = new QuestionSet();
                        questionSet.CategoryId = db.Categories.First(c => c.Name == row.Category).CategoryId;
                        questionSet.Question = new Question();
                        questionSet.Question.QuestionText = row.Question;
                        questionSet.Level = row.Level.GetValueOrDefault(0);
                        questionSet.IsVisible = row.IsVisible.GetValueOrDefault(false);
                        questionSet.Answers = new List<Answer>();
 
                        index++;
                        while (index !=rows.Count && rows[index].Question == string.Empty)
                        {
                            var correctAnswer = new Answer()
                            {
                                AnswerText = rows[index].Answer,
                                Order = rows[index].Order.GetValueOrDefault(0),
                                IsCorrect = rows[index].CorrectAnswer.GetValueOrDefault(false)
                            };
                           questionSet.Answers.Add(correctAnswer);
                           
                           index++;
                        }
                        db.QuestionSet.Add(questionSet);
                        
                    }
                    db.SaveChanges();
                }
            }
            
        }
    }
}